/*
 * ID3.cpp
 *
 *  Created on: 2018年9月17日
 *      Author: fangxia722
 */

#include <ID3.h>
#include<map>
using namespace std;
double ID3::selectFun(vector<int> index_data,int index_feature) {
	double result = 0;
	map<double,int> C;
	for(int i=0;i<index_data.size();i++){
		double label = datas->getData(index_data[i]).y;
		if(C.find(label)==C.end()){
			C[label]=0;
		}
		C[label]=C[label]+1;
	}
	map<double,int>::iterator iter = C.begin();
	for(;iter!=C.end();iter++){
		double pre = ((double)iter->second)/((double)index_data.size());
		result-=(log(pre)/log(2.0))*pre;
	}
	double HD = result;
	Feature feature = (*features)[index_feature];
	for(int i=0;i<feature.getValues().size();i++){
		double sum = 0.0;
		double value = feature.getValues()[i];
		int Di = 0;
		map<double,int> Dik;
		for(int j=0;j<index_data.size();j++){
			double xFeature = datas->getData(index_data[j]).x->get(index_feature);
			double y =  datas->getData(index_data[j]).y;
			if(xFeature==value){
				Di++;
				if(Dik.find(y)==Dik.end()){
					Dik[y]=0;
				}
				Dik[y] = Dik[y]+1;
			}
		}
		map<double,int>::iterator iiter = Dik.begin();
		for(;iiter!=Dik.end();iiter++){
			double pre = ((double)iiter->second)/((double)(Di));
			sum += pre*(log(pre)/log(2.0));
		}
		result +=((double)(Di))*sum/((double)index_data.size());
		if(this->mode==1){
			result = result/HD;
		}
	}
	return result;
}


